package com.ygqh.baby.handler;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.foxinmy.weixin4j.http.HttpHeaders;
import com.ygqh.baby.ao.Message;
import com.ygqh.baby.ao.OffShop;
import com.ygqh.baby.exception.YgHttpException;
import com.ygqh.baby.http.YgRequestExecutor;
import com.ygqh.baby.http.YgResponse;
import com.ygqh.baby.kids.entity.bo.KidsProductExt;
import com.ygqh.baby.mapper.YgProductMapper;
import com.ygqh.baby.po.YgProduct;
import com.ygqh.baby.utils.DateConvertUtils;
import com.ygqh.baby.utils.ExceptionUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 〈〉
 *
 * @author guohao
 * @date 2019/6/4 10:06
 * @since 1.0.0
 */
@Component
public class ProductPushHandler {

    private Logger logger = LoggerFactory.getLogger(this.getClass());
    private YgRequestExecutor ygRequestExecutor = new YgRequestExecutor();

    private final ExecutorService executorService = Executors.newFixedThreadPool(2);

    @Value("${kids.push.product.url}")
    private String kidsPushUrl;

    @Value("${kids.push.productPreDate.url}")
    private String kidsPreDatePushUrl;

    @Value("${off.push.product.url}")
    private String offPushUrl;

    @Value("${off.push.productPreDate.url}")
    private String offPreDatePushUrl;

    @Autowired
    private YgProductMapper ygProductMapper;

    public Message pushProductToOffShop(Long productId, String operator, OffShop[] offShops) {

        StringBuilder errorMsg = new StringBuilder();
        for (OffShop offShop : offShops) {
            Message message = doPushProductToOffShop(productId, operator, offShop);
            if (!Message.Type.success.equals(message.getType())) {
                errorMsg.append(message.getContent()).append(";");
            }
        }
        if (errorMsg.length() == 0) {
            return Message.success(null);
        }
        return Message.error(errorMsg.toString(), null);
    }

    private Message doPushProductToOffShop(Long productId, String operator, OffShop offShop) {
        String pushProductUrl = getPushProductUrl(offShop);
        KidsProductExt kidsProductExt = ygProductMapper.selectProductInfoForKids(productId);


        if (kidsProductExt == null) {
            return Message.error("商品信息异常，推送失败", null);
        }
        JSONObject saveYgProductReq = new JSONObject();
        saveYgProductReq.put("platformNo", offShop.getPlatformNo());
        saveYgProductReq.put("operator", operator);
        saveYgProductReq.put("productList", JSONArray.parseArray(JSONArray.toJSONString(Collections.singletonList(kidsProductExt))));
        HttpHeaders headers = new HttpHeaders();
        headers.add("content-type", "application/json; charset=UTF-8");
        YgResponse response;
        try {
            response = ygRequestExecutor.post(pushProductUrl, headers, saveYgProductReq.toJSONString());
        } catch (YgHttpException e) {
            e.printStackTrace();
            return Message.error("推送请求访问异常", null);
        }
        JSONObject asJson = response.getAsJson();
        if ("200".equals(asJson.getString("code"))) {
            if (OffShop.Kids.equals(offShop)) {
                YgProduct product = new YgProduct();
                product.setId(productId);
                product.setPushKids(Boolean.TRUE);
                ygProductMapper.updateByPrimaryKeySelective(product);
            }
            return Message.success(asJson.get("data"));
        }
        return Message.error(asJson.getString("msg"), null);
    }

    /**
     * 推送商品预售期到新世界（异步）
     *
     * @param ygProduct 商品信息
     * @param preDate   预售日期
     * @param offShops
     */
    public void pushProductPreDateToOffShop(YgProduct ygProduct, Date preDate, OffShop[] offShops) {

        for (OffShop shop : offShops) {
            doPushProductPreDateToOffShop(ygProduct, preDate, shop);
        }
    }

    private void doPushProductPreDateToOffShop(YgProduct ygProduct, Date preDate, OffShop offShop) {
        if (!ygProduct.getPushKids()) {
            return;
        }
        String pushProductPreDateUrl = getPushProductPreDateUrl(offShop);
        executorService.execute(() -> {
            Map<String, String> data = new HashMap<>();
            if (preDate != null) {
                data.put("preDate", DateConvertUtils.format(preDate));
            }
            data.put("productCode", ygProduct.getProductCode());
            data.put("platformNo", offShop.getPlatformNo());
            try {
                YgResponse response = ygRequestExecutor.post(pushProductPreDateUrl, data);
                JSONObject asJson = response.getAsJson();
                if (!"200".equals(asJson.getString("code"))) {
                    logger.error(asJson.getString("msg"));
                }
            } catch (YgHttpException e) {
                e.printStackTrace();
                logger.error("推送请求访问异常, " + ExceptionUtil.getExceptionMsg(e), e);
            }
        });
    }

    private String getPushProductUrl(OffShop offShop) {
        if (OffShop.Kids.equals(offShop)) {
            return kidsPushUrl;
        } else if (OffShop.TaiYangGong.equals(offShop)) {
            return offPushUrl;
        }
        throw new RuntimeException("未知的线下店铺");
    }

    private String getPushProductPreDateUrl(OffShop offShop) {
        if (OffShop.Kids.equals(offShop)) {
            return kidsPushUrl;
        } else if (OffShop.TaiYangGong.equals(offShop)) {
            return offPreDatePushUrl;
        }
        throw new RuntimeException("未知的线下店铺");

    }
}
